package org.jeecg.modules.notice;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.cmbCloudDirectLink.utils.VerifySig;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.constant.RedisCacheConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiBusinessBank;
import org.jeecg.modules.manage.entity.CaishuiFinanceRecord;
import org.jeecg.modules.manage.entity.CaishuiRecharge;
import org.jeecg.modules.manage.mapper.MCaishuiRechargeMapper;
import org.jeecg.modules.manage.service.IMCaishuiBusinessService;
import org.jeecg.modules.manage.service.IMCaishuiFinanceRecordService;
import org.jeecg.modules.manage.service.IMCaishuiRefundRecordService;
import org.jeecg.modules.manage.service.IMCaishuiTaskSettleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description: 云直联通知
 * @Author: yfkj
 * @Date:   2023-03-03
 * @Version: V1.0
 */
@RestController
@RequestMapping("/noticeApi")
@Slf4j
public class CMBNotice {

	@Autowired
	private IMCaishuiFinanceRecordService imCaishuiFinanceRecordService;
	@Resource
	private MCaishuiRechargeMapper mCaishuiRechargeMapper;
	@Resource
	private IMCaishuiBusinessService imCaishuiBusinessService;
	@Resource
	private IMCaishuiRefundRecordService imCaishuiRefundRecordService;
	@Autowired
	private RabbitMqClient rabbitMqClient;
	@Autowired
	private RedisUtil redisUtil;


	/**
	 * 招行银企直联通知
	 *
	 * 账务变动通知（YQN01010）
	 * 回单结果通知（YQF01010）
	 * 支付结果通知（YQN02030）
	 * 代发结果通知（YQN03010）
	 * 代发明细对账单结果通知（YQF03010）
	 * 代扣结果通知（YQN03030）
	 * 汇入汇款通知（YQN07110）
	 * 维护通知（YQSYSTEM）
	 *
	 * @param jsonObject
	 * @return
	 */
	@PostMapping(value = "/reqNotice")
	public Result<String> receiptNotice(@RequestBody JSONObject jsonObject) {
		log.info("招行银企直联通知响应报文：" + jsonObject);
		String sigdat = jsonObject.getString("sigdat");
		//代签名原文
		jsonObject.put("sigdat","__signature_sigdat__");
		String resSignSource = jsonObject.toJSONString();
		//验签
		if(!VerifySig.cmbSM2Verify(resSignSource,sigdat)){
			return Result.error("请求签名校验不通过！");
		}

		/**业务处理*/
		String nottyp = jsonObject.getString("nottyp");//通知类型
		if("YQN01010".equals(nottyp)){//账务变动通知
			//通知内容
			String notdat = jsonObject.getString("notdat");
			log.info("账务变动通知（YQN01010）响应报文：" + notdat);
			if(oConvertUtils.isNotEmpty(notdat)){
				JsonObject object = new GsonBuilder().create().fromJson(notdat, JsonObject.class);
				JsonObject msgdat = object.getAsJsonObject("msgdat");
				/**添加财务到账记录*/
				CaishuiFinanceRecord financeRecord = new CaishuiFinanceRecord();
				financeRecord.setCreateTime(new Date());
				financeRecord.setResultText(object.toString());
				imCaishuiFinanceRecordService.save(financeRecord);

				String msgtyp = object.get("msgtyp").getAsString();//通知子类型
				if("NCCRTTRS".equals(msgtyp)){//到账通知
					/**新增充值记录*/
					String amtcdr = msgdat.get("amtcdr").getAsString();//交易方向：D-借方（支出），C-贷方（收入）
					String trscod = oConvertUtils.isEmpty(msgdat.get("trscod")) ? "" : msgdat.get("trscod").getAsString();//交易类型
					if("C".equals(amtcdr)){// 收入
						if (trscod.indexOf("CPUA")!=-1 || trscod.indexOf("NPT2")!=-1) {// 转账汇款
							log.info("=======到账通知(NCCRTTRS)=====账户收入================：" + msgdat);
							String refnbr = msgdat.get("refnbr").getAsString();//记账流水号
							String accnbr = msgdat.get("accnbr").getAsString();//帐号
							//开通收方识别功能的账户可以通过此码识别付款方
							String dmanbr = oConvertUtils.isEmpty(msgdat.get("frmcod")) ? "" : msgdat.get("frmcod").getAsString();//企业识别码（记账子单元编码）
							//判断记录是否已添加
							long count = mCaishuiRechargeMapper.selectCount(new LambdaQueryWrapper<CaishuiRecharge>()
									.eq(CaishuiRecharge::getOrderNo,refnbr));
							if(count <= 0){
								//根据账号和记账子单元编号查询商户银行信息
								CaishuiBusinessBank businessBank = mCaishuiRechargeMapper.queryBusinessBank(accnbr, dmanbr);
								if(oConvertUtils.isNotEmpty(businessBank)){
									//商户信息
									CaishuiBusiness business = imCaishuiBusinessService.getById(businessBank.getBusinessId());
									if (oConvertUtils.isEmpty(business)) return Result.error("商户信息错误！");
									//新增充值记录
									String rpynam = msgdat.get("rpynam").getAsString();//付方名称
									String rpyacc = msgdat.get("rpyacc").getAsString();//付方账号
									String trxamt = msgdat.get("c_trsamt").getAsString();//交易金额
									String naryur = oConvertUtils.isEmpty(msgdat.get("naryur")) ? "" : msgdat.get("naryur").getAsString();//交易摘要
									CaishuiRecharge recharge = new CaishuiRecharge();
									recharge.setCreateBy(businessBank.getCreateBy());
									recharge.setCreateTime(new Date());
									recharge.setCompanyId(businessBank.getServiceCompanyId());
									recharge.setBusinessId(businessBank.getBusinessId());
									recharge.setTenantId(businessBank.getTenantId());
									recharge.setUserId(business.getUserId());
									recharge.setChannelBusinessId(business.getChannelBusinessId());
									recharge.setOrderNo(refnbr);
									recharge.setMainAccount(accnbr);
									recharge.setSubUnitName(businessBank.getAccountName());
									recharge.setSubUnitCode(dmanbr);
									recharge.setPaymentAccountName(rpynam);
									recharge.setPaymentAccount(rpyacc);
									recharge.setCollectionAccountName(businessBank.getName());
									recharge.setCollectionAccount(businessBank.getAccount());
									recharge.setAmount(Double.valueOf(trxamt));
									recharge.setRemark(naryur);
									recharge.setStatus(1);
									recharge.setCheckStatus(1);
									recharge.setReceiptTime(new Date());
									mCaishuiRechargeMapper.insert(recharge);
								}
							}
						}
					}
				}
				if("NCDBTTRS".equals(msgtyp)){//付款通知
					//TODO 付款通知事件

				}
			}
		}
		if("YQN03010".equals(nottyp)){//代发通知
			//通知内容
			String notdat = jsonObject.getString("notdat");
			log.info("代发结果通知（YQN03010）响应报文：" + jsonObject);
			if(oConvertUtils.isNotEmpty(notdat)){
				JsonObject object = new GsonBuilder().create().fromJson(notdat, JsonObject.class);
				String msgtyp = object.get("msgtyp").getAsString();//通知子类型
				if("FIN".equals(msgtyp)){//业务完成通知
					//通知内容
					JsonObject msgdat = object.getAsJsonObject("msgdat");
					//批次信息
					JsonObject agcInfo = msgdat.getAsJsonObject("agcInfo");
					//明细信息
//					JsonArray detailInfo = msgdat.getAsJsonArray("detailInfo");
					String yurref = agcInfo.get("yurref").getAsString();//业务参考号

					/**同步处理*/
//					iMCaishuiTaskSettleService.handleTaskSettle(yurref);

					/**异步处理*/
					BaseMap map = new BaseMap();
					map.put("orderNo", yurref);
					//防止重复提交
					redisUtil.incr(RedisCacheConstant.YSW_BATCH_AND_DETAIL_REPEAT_CACHE + ":" + yurref,1);
					rabbitMqClient.sendMessage("caisui_batch_and_detail_queue", map);
				}
				if("RFD".equals(msgtyp)){//代发退票通知
					JsonObject msgdat = object.getAsJsonObject("msgdat");
					//TODO 处理代发退票事件

				}
			}
		}
		if("YQN02030".equals(nottyp)) {//支付结果通知
			//通知内容
			String notdat = jsonObject.getString("notdat");
			log.info("支付结果通知（YQN03010）响应报文：" + jsonObject);
			if(oConvertUtils.isNotEmpty(notdat)) {
				JsonObject object = new GsonBuilder().create().fromJson(notdat, JsonObject.class);
				String msgtyp = object.get("msgtyp").getAsString();//通知子类型
				if("FINS".equals(msgtyp)) {//业务完成通知
					//通知内容
					JsonObject msgdat = object.getAsJsonObject("msgdat");
					//支付明细
					JsonObject trsInfo = msgdat.getAsJsonObject("trsInfo");
					String yurRef = trsInfo.get("yurRef").getAsString();//业务参考号
					//企银支付业务查询
					imCaishuiRefundRecordService.queryRefundResult(yurRef);
				}
				if("FINB".equals(msgtyp)){//支付退票通知
					JsonObject msgdat = object.getAsJsonObject("msgdat");
					//TODO 处理代发退票事件
				}
			}
		}
		return Result.OK("通知成功！");
	}


}
